package com.example.teamtribe.main.club.manage.feedback.apply;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.common.model.UserModel;
import com.example.teamtribe.database.MegId;
import com.example.teamtribe.database.TeamRequest;
import com.example.teamtribe.utils.Utility;

import java.util.ArrayList;
import java.util.List;

public class AppListPresenter implements AppListContract.Presenter {

    private AppListContract.View view;

    public AppListPresenter(AppListContract.View view) {
        this.view = view;
    }

    @Override
    public void start(int teamId) {
        view.clearRequest();
        List<TeamRequest> requests = AppListModel.getInstance().getLocal(teamId);
        if (requests == null) {
            requests = new ArrayList<>(0);
        }
        view.addRequest(requests);
        getRequest();
    }

    @Override
    public void getRequest() {
        UserModel.getInstance().getMessages(Utility.getToken(), 3, new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                ArrayList<MegId> ids = bundle.getParcelableArrayList("messages");
                if (ids == null || ids.isEmpty()) {
                    view.loadComplete();
                    return;
                }
                for (MegId megId : ids) {
                    getRequestInfo(megId.getId());
                }
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
            }
        });
    }

    @Override
    public void agree(final int position, final TeamRequest request) {
        view.showProgress();
        final int result = 1;
        AppListModel.getInstance().response(Utility.getToken(), request.getRealId(), result, "", new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                request.setResult(result);
                request.saveOrUpdate();
                view.notifyItemChanged(position, request);
                view.hideProgress();
            }

            @Override
            public void failure(String meg) {
                view.hideProgress();
                view.showToast(meg);
            }
        });
    }

    private void getRequestInfo(int id) {
        AppListModel.getInstance().getRequests(Utility.getToken(), id, new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                TeamRequest request = bundle.getParcelable("request");
                request.saveOrUpdate();
                view.addRequest(request);
                view.loadComplete();
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
            }
        });
    }
}
